const ColorUISdk = require('../../mp-sdk/index')

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url:'http://192.168.134.31:5000'
    }
  }
})

sdk.request = sdk.request.bind(sdk);

// 使用微信官方的UserInfo类型
type UserInfo = WechatMiniprogram.UserInfo;

Page({
  data: {
    phone: '',
    password: '',
    userInfo: {
      avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      nickName: '',
    } as UserInfo,
    hasUserInfo: false,
    avatarSet: false, // 新增：跟踪头像是否已设置
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
  },

  onPhoneChange(e: any) {
    this.setData({ phone: e.detail.value })
  },

  onPasswordChange(e: any) {
    this.setData({ password: e.detail.value })
  },

  async login() {
    const { phone, password } = this.data
    
    if (!phone || !password) {
      wx.showToast({ title: '请输入手机号和密码', icon: 'none' })
      return
    }
    
    try {
      wx.showLoading({ title: '登录中...' })
      
      const res = await sdk.request({
        url: '/auth/login',
        method: 'POST',
        data: { phone, password }
      })
      
      wx.hideLoading()
      
      if (res.code === 0) {
        // 处理账号登录的用户信息格式，确保包含user_id字段
        const userInfo = {
          ...res.data.user_info,
          user_id: res.data.user_info.user_id || res.data.user_info._id, // 确保使用user_id字段
          avatarUrl: res.data.user_info.avatar_url || this.data.userInfo.avatarUrl,
          nickName: res.data.user_info.nickname || this.data.userInfo.nickName
        }
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('token', res.data.token || res.data.user_info.token)
        wx.switchTab({ url: '/pages/home/home' })
      } else {
        wx.showToast({ title: res.msg || '登录失败', icon: 'none' })
      }
    } catch (error) {
      wx.hideLoading()
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  goToRegister() {
    wx.navigateTo({ url: '/pages/register/register' })
  },

  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail;
    if (!avatarUrl) {
      return;
    }
    this.setData({
      'userInfo.avatarUrl': avatarUrl,
      avatarSet: true,
    });
    this.checkUserInfoComplete();
    // 同步到全局
    const app = getApp();
    if (app && app.globalData) {
      app.globalData.userInfo = this.data.userInfo;
    }
  },

  onInputNickname(e: any) {
    const nickName = e.detail.value;
    this.setData({
      'userInfo.nickName': nickName,
    });
    this.checkUserInfoComplete();
    // 同步到全局
    const app = getApp();
    if (app && app.globalData) {
      app.globalData.userInfo = this.data.userInfo;
    }
  },

  // 检查用户信息是否完整
  checkUserInfoComplete() {
    const { nickName } = this.data.userInfo;
    const { avatarSet } = this.data;
    
    this.setData({
      hasUserInfo: !!nickName && avatarSet
    });
  },

  // 旧方式：获取用户信息（兼容低版本）
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          avatarSet: true
        });
        // 同步到全局
        const app = getApp();
        if (app && app.globalData) {
          app.globalData.userInfo = res.userInfo;
        }
      },
      fail: (err) => {
        console.error('用户拒绝授权：', err);
        wx.showToast({
          title: '请允许授权以完成登录',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },

  // 微信登录按钮点击
  handleWechatLogin() {
    console.log('登录状态', {
      hasUserInfo: this.data.hasUserInfo,
      userInfo: this.data.userInfo
    });
    
    if (this.data.hasUserInfo) {
      this.wechatLogin(this.data.userInfo)
    } 
    else if (this.data.canIUseGetUserProfile) {
      this.getUserProfile()
    }
    else {
      wx.showToast({
        title: '请完善头像和昵称',
        icon: 'none'
      })
    }
  },

  // 微信登录逻辑
  async wechatLogin(userProfile: UserInfo) {
    try {
      // 每次登录获取新code
      const loginRes = await wx.login()
      const code = loginRes.code
      
      if (!code) {
        wx.showToast({ title: '获取登录凭证失败', icon: 'none' })
        return
      }
      
      wx.showLoading({ 
        title: '微信登录中...',
        mask: true
      })
      
      // 调整数据结构，确保与后端期望的一致
      const res = await sdk.request({
        url: '/api/auth/wxlogin',
        method: 'POST',
        data: { 
          code,
          userInfo: {
            avatarUrl: userProfile.avatarUrl,
            nickName: userProfile.nickName,
            gender: userProfile.gender,
            country: userProfile.country,
            province: userProfile.province,
            city: userProfile.city
          }
        }
      }, true)
      
      wx.hideLoading()
      
      if (res.code === 0) {
        // 统一用户信息格式，确保包含user_id字段
        const userInfo = {
          ...res.data,
          user_id: res.data.user_id || res.data._id, // 确保使用user_id字段
          avatarUrl: res.data.avatar_url || userProfile.avatarUrl,
          nickName: res.data.nickname || userProfile.nickName
        }
        
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('token', res.data.token)
        
        wx.switchTab({ url: '/pages/home/home' })
      } else {
        wx.showToast({ title: res.msg || '登录失败', icon: 'none' })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('微信登录错误:', error)
      
      let errorMsg = '网络错误';
      if (typeof error === 'object' && error !== null && 'errMsg' in error) {
        if (error.errMsg.includes('404')) {
          errorMsg = '接口不存在，请检查URL';
        } else if (error.errMsg.includes('url not in domain list')) {
          errorMsg = '请检查域名配置';
        } else if (error.errMsg.includes('400')) {
          errorMsg = '参数错误，请检查输入';
        } else if (error.errMsg.includes('500')) {
          errorMsg = '服务器错误，请稍后再试';
        }
      }
      
      wx.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 3000
      })
    }
  }
})